package com.stylefeng.guns.modular.biz.service.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.stylefeng.guns.common.constant.DSEnum;
import com.stylefeng.guns.common.persistence.dao.StuActMapper;
import com.stylefeng.guns.common.persistence.dao.StuMapper;
import com.stylefeng.guns.common.persistence.model.StuAct;
import com.stylefeng.guns.common.persistence.model.Student;
import com.stylefeng.guns.core.mutidatasource.annotion.DataSource;
import com.stylefeng.guns.modular.biz.service.StuService;
import com.stylefeng.guns.modular.system.dao.StuDao;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;

@Service
public class StuServiceImpl implements StuService {
    @Resource
    StuDao stuDao;
    @Resource
    StuMapper stuMapper;
    @Resource
    StuActMapper stuActMapper;

    @Override
    @DataSource(name = DSEnum.DATA_SOURCE_BIZ)
    public List<Map<String, Object>> selectStudents(Map<String, Object> params) {
        return stuDao.selectStudents(params);
    }

    @Override
    @Transactional(readOnly = false)
    public void insert(Student student, List<StuAct> list) {

        stuMapper.insert(student);
        //批量关联活动中间表
        for(StuAct sa : list) {
            sa.setStuid(student.getStuid());
            stuActMapper.insert(sa);
        }
    }

    @Override
    @Transactional(readOnly = false)
    public void updateStudent(Student student,List<StuAct> list) {
        //更新学生信息
        stuMapper.updateById(student);
        //删除学生活动关联
        EntityWrapper ew=new EntityWrapper();
        ew.where("stuid={0}",student.getStuid());
        stuActMapper.delete(ew);
        //插入新的关联
        for(StuAct sa : list) {
            sa.setStuid(student.getStuid());
            stuActMapper.insert(sa);
        }

    }

    @Override
    @Transactional(readOnly = false)
    public void deleteStudents(Student student) {
        stuMapper.deleteById(student);
        //删除学生活动关联
        EntityWrapper ew=new EntityWrapper();
        ew.where("stuid={0}",student.getStuid());
        stuActMapper.delete(ew);
    }

    @Override
    public Student selectStuById(Integer stuId) {
        return stuMapper.selectById(stuId);
    }

    @Override
    public List<StuAct> selectStuActByStu(Student student) {
        EntityWrapper ew=new EntityWrapper();
        ew.where("stuid={0}",student.getStuid());
        return stuActMapper.selectList(ew);
    }


}
